<template>
  <div class="external-links">
    <search-table
      :data="externalLinksData"
      :columns="columns"
      :page.sync="queryParams.pageIndex"
      :size.sync="queryParams.pageSize"
      :total="externalLinksTotal"
      :loading="externalLinksLoading"
      @queryFun="getNewData">
      <template slot="search">
        <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建外部链接</Button>
        <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshList()">
          <i class="el-icon-refresh-right" />
        </Button>
      </template>
          <Modal
              v-model="modalData.show"
              :title="`创建外部参考链接`"
              @on-visible-change="changeVisible"
              class="my-modal">
            <Form
                ref="formInline"
                :label-width="100"
                :model="formInline"
                :rules="ruleInline">
              <FormItem prop="name" label="组件名称">
                <Input clearable v-model="formInline.name" disabled></Input>
              </FormItem>
              <FormItem prop="link" label="链接地址">
                <Input clearable v-model="formInline.link"></Input>
              </FormItem>
              <FormItem prop="type"  label="类型">
                <Select filterable transfer filterable clearable v-model="formInline.type" placeholder="">
                  <Option v-for="(item, index) in typeOtions" :value="index" :key="index">{{ item }}</Option>
                </Select>
              </FormItem>
            </Form>
            <div slot="footer" class="footer">
              <Button @click="modalData.show = false">取消</Button>
              <Button @click="saveExternalLinks" :loading="modalData.loading" type="primary">确定</Button>
            </div>
          </Modal>
    </search-table>
  </div>
</template>

<script>
import {
  queryProductComponentLinkList,
  addProductComponentLink,
  updateProductComponentLink,
  deleteProductComponentLink
} from '../api/productComponentLink'
import { validateUrl, validateName } from '@/libs/reg'
import {LINK_TYPE_OPTIONS} from '../../paramsConfig'
import {deleteSystemUrl} from "../api/system";
import {linkTypeEscape} from "../logic/assetLogic";


export default {
  name: 'ExternalLinks',
  props: {
    disabledOperation: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      externalLinksLoading:false,
      externalLinksData:[],
      externalLinksTotal:0,
      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      deleteFn: deleteProductComponentLink,
      searchFn: queryProductComponentLinkList,
      typeOtions: LINK_TYPE_OPTIONS,
      modalData: {
        show: false,
        loading: false
      },
      currentItem: {},
      resData: {
        total: 0,
        list: [],
        loading: true
      },
      formInline: {
        name: '',
        link: '',
        type: '',
      },
      columns: [
        {
          title:'组件名称',
          key:'productComponentName',
        },
        {
          title:'链接',
          key:'link'
        },
        {
          title:'类型',
          key:'type',
          render: (h, params) => {
            let ret = linkTypeEscape(params.row.type)
            return h('Tag', {
              props: {
                color: ret.color
              },
              style: {
                width: '96px',
                'text-align': 'center'
              }
            }, ret.text)
          }
        },
        {
          title: '操作',
          slot: 'action',
          width: 110,
          opList: [
            {
              txt: '修改',
              fun:(obj)=>{
                this.showModal(obj)
              },
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个部件吗？',
              fun:(obj)=>{
                this.deleteItem(obj.id)
              },
              isDelete:true,
            },
          ]
        }
      ],
      ruleInline: {
        name: [
          { required: true, message: `组件名称不能为空`, trigger: 'blur,change' },
          { type:'string',max: 64,trigger:'blur,change',message:'最多输入64个字符' },
          { validator: validateName, trigger: 'blur,change' }
        ],
        link: [
          { required: true, message: '链接地址不能为空', trigger: 'blur,change' },
          { type:'string',max: 1000,trigger:'blur',message:'最多输入1000个字符'},
          { validator: validateUrl, trigger: 'blur,change' }
        ],
        type: [
          { required: true, type:'number', message: '类型不能为空', trigger: 'blur,change' },
        ],
      },
      isAdd: false
    }
  },
  methods: {
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
      if (!type) {
        this.$refs.formInline.resetFields()
        this.modalData.loading = false
      }
    },
    // 初始化数据
    init(obj) {
      this.currentItem = obj
      this.queryParams = {
        pageIndex:1,
       pageSize:10,
     }
      this.getNewData()
    },
    refreshList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
      }
      this.getNewData()
    },
    getNewData(){
      this.externalLinksLoading = true;
      let params = {...this.queryParams}
      params.productComponentId = this.currentItem.id
      queryProductComponentLinkList(params).then(res=>{
        if(res.code===1){
          this.externalLinksData = res.data.items;
          this.externalLinksTotal = res.data.total;
        }else{
          this.$Message.error(res.message)
        }
      }).finally(()=>{
        this.externalLinksLoading = false
      })
    },
    // 打开模态框
    showModal(data) {
      this.isAdd = !data
      this.modalData.show = true
      let obj = data || { name: this.currentItem.name, productComponentId: this.currentItem.id }
      this.formInline = Object.assign({}, obj)
      if (!obj.name && obj.productComponentName) { // 当name字段没有值，而productComponentName字段有值时，覆盖name字段
        this.$set(this.formInline, 'name', obj.productComponentName)
      }
    },
    // 删除外部链接
    deleteItem(id) {
      deleteProductComponentLink([id]).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(`删除成功`)
        // 删除后展示当前页，当前页没有数据展示前一页
        this.queryParams.pageIndex = (this.externalLinksData.length === 1 && this.queryParams.pageIndex > 1) ?
          this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
        this.getNewData();
      }).catch(() => {
        this.$Message.error(`删除异常`)
      })
    },
    // 保存修改外部参考链接
    saveExternalLinks() {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          this.modalData.loading = true
          let apiName = this.isAdd ? addProductComponentLink : updateProductComponentLink
          if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
            delete this.formInline.id
          }
          apiName(this.formInline).then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message)
              return
            }
            // 创建成功
            this.$Message.success(`${this.isAdd ? '创建' : '修改'}外部参考链接成功`)
            this.getNewData()
            this.modalData.show = false
          }).catch(() => {
            this.$Message.error(`${this.isAdd ? '创建' : '修改'}外部参考链接异常`)
          }).finally(() => {
            this.modalData.loading = false
          })
        }
      })
    },
  }
}
</script>

<style scoped>
.external-links {
  width: 100%;
  height: 100%;
}
.external-links /deep/ .list-page {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  border-radius: 0;
}
</style>
